﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using PolePositionMobileUtilityData;
using System.Data;
using PolePositionMobileUtilityEntity;
using System.IO;
using PolePositionMobileUtilityGeneral;

namespace PolePositionMobileUtilityLogic
{
    public class LImage
    {
        public static void Delete(int ImageId)
        {
            DImage.Delete(ImageId);
        }
        
        public static void Insert(List<EImage> images, int inspectionId)
        {
            int imageCounter = 1;
            foreach (EImage i in images)
            {
                FileInfo _file = new FileInfo(PPIConstants.K_ImagesFolder + i.FileName);
                if (_file.Exists && !i.IsDeleted && i.Id == Int32.MinValue)
                {
                    while (File.Exists(PPIConstants.K_ImagesFolder + "Photo_" + inspectionId + "_" + imageCounter + ".jpg"))
                    {
                        imageCounter++; 
                    }
                    i.FileName = _file.CopyTo(PPIConstants.K_ImagesFolder + "Photo_"+inspectionId+"_"+imageCounter+".jpg",true).Name;
                    DImage.Insert(i.FileName, inspectionId, Int32.MinValue);
                    imageCounter++;
                }
            }
        }

        public static List<EImage> GetAllByInspection(int inspectionId)
        {
            DataTable _dt = DImage.GetAllByInspection(inspectionId);
            List<EImage> _imageList = new List<EImage>();
            EImage _image;
            foreach (DataRow dr in _dt.Rows)
            {
                _image = new EImage();
                _image.Id = ConvertMobileHelper.ToInt32(dr["ImageId"]);
                _image.FileName = ConvertMobileHelper.Tostring(dr["Filename"]);
                _image.UtilityInspection.Id = ConvertMobileHelper.ToInt32(dr["UtilityInspectionFk"]);
                _image.UtilityInspectionResult.Id = ConvertMobileHelper.ToInt32(dr["UtilityInspectionResultFk"]);
                _imageList.Add(_image);
            }
            return _imageList;
        }

        public static void DeleteByInspection(int inspectionId, List<EImage> images)
        {
            foreach (EImage  i in images)
            {
                FileInfo f = new FileInfo(PPIConstants.K_ImagesFolder + i.FileName);
                if (f.Exists && i.IsDeleted)
                {
                    f.Delete();
                    DImage.Delete(i.Id);
                }
                    
            }
        }
    }
}
